package org.ricks.net;

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author chenwei
 * @Description:
 * @date 2022/10/2018:27
 */
public class SessionManager {

    private static final SessionManager INSTANCE = new SessionManager();

    public static SessionManager get() {
        return INSTANCE;
    }

    private Map<Long, AioSession> sessions = new ConcurrentHashMap<>();

    public AioSession getSession(long sessionId) {
        return sessions.get(sessionId);
    }

    public List<AioSession> getSessions() {
        return sessions.values().stream().toList();
    }

    public void  putSession(long sessionId, AioSession session) {
        sessions.put(sessionId,session);
    }

    public void removeSession(long sessionId) {
        sessions.remove(sessionId);
    }

    public void closeAll() {
        while (!sessions.isEmpty()) {
            Set<Long> ids = sessions.keySet();
            ids.forEach(id -> sessions.remove(id).close(true));
        }
    }
}
